# ==== control_unit.py ====
class ControlUnit:
    def __init__(self):
        self.signals = {
            "RegDst": 0, "ALUSrc": 0, "MemtoReg": 0, "RegWrite": 0,
            "MemRead": 0, "MemWrite": 0, "Branch": 0, "ALUOp": "00"
        }

    def decode(self, opcode):
        # 重置所有信号
        for key in self.signals:
            self.signals[key] = 0
        self.signals["ALUOp"] = "00"

        # R型指令
        if opcode == 0x00:
            self.signals["RegDst"] = 1
            self.signals["RegWrite"] = 1
            self.signals["ALUOp"] = "10"
        # lw指令
        elif opcode == 0x23:
            self.signals["ALUSrc"] = 1
            self.signals["MemtoReg"] = 1
            self.signals["RegWrite"] = 1
            self.signals["MemRead"] = 1
            self.signals["ALUOp"] = "00"
        # sw指令
        elif opcode == 0x2B:
            self.signals["ALUSrc"] = 1
            self.signals["MemWrite"] = 1
            self.signals["ALUOp"] = "00"
        # beq指令
        elif opcode == 0x04:
            self.signals["Branch"] = 1
            self.signals["ALUOp"] = "01"
        # addi指令
        elif opcode == 0x08:
            self.signals["ALUSrc"] = 1
            self.signals["RegWrite"] = 1
            self.signals["ALUOp"] = "00"